﻿using MediatR;
using T_Rbac_APi.Application.Command.Jobs;
using T_Rbac_Rep.Interface;

namespace T_Rbac_APi.Application.CommandHandler.JobsHandler
{
    public class JobDeleteListHandlers : IRequestHandler<JobDeleteListCommand, int>
    {
        private readonly IjobRep ijobRep;
        private readonly IjobMenuesRep ijobMenuesRep;
        private readonly IOperator ioperator;

        public JobDeleteListHandlers(IjobRep ijobRep, IjobMenuesRep ijobMenuesRep, IOperator ioperator)
        {
            this.ijobRep = ijobRep;
            this.ijobMenuesRep = ijobMenuesRep;
            this.ioperator = ioperator;
        }

        public async Task<int> Handle(JobDeleteListCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var ids = (!string.IsNullOrEmpty(request.ids)) ? request.ids.Split(',').Select(x => Convert.ToInt32(x)).ToArray() : null;
                if (ids == null)
                {
                    return await Task.FromResult(-2);
                }
                var operatorlist = await ioperator.GetvaluesByResult(x => ids.Contains(x.Orid));
                if (operatorlist != null)
                {
                    return await Task.FromResult(-3);
                }
                var joblist = await ijobRep.GetvaluesByResult(x => ids.Contains(x.Jid));
                int resultjob = await ijobRep.DeleteRange(joblist.ToList());
                if (resultjob > 0)
                {
                    var menuesList = await ijobMenuesRep.GetvaluesByResult(x => ids.Contains(x.Jjid));
                    await ijobMenuesRep.DeleteRange(menuesList.ToList());
                }
                return await Task.FromResult(1);
            }
            catch (Exception)
            {
                return await Task.FromResult(-1);
                throw;
            }
         
        }
    }
}
